import sys
import pygame
from bullet import Bullet
from alien import Alien
from time import sleep

def check_events(screen, settings, ship, bullets):
    """检测游戏所有事件"""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        # 响应键盘鼠标事件
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event, screen, settings, ship, bullets)
        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)


def check_keydown_events(event, screen, settings, ship, bullets):
    """检测键盘事件"""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_SPACE:
        fire(screen, settings, ship, bullets)
    elif event.key == pygame.K_q:
        sys.exit()


def check_keyup_events(event, ship):
    """检测离开键盘事件，用于停止飞船移动"""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    if event.key == pygame.K_LEFT:
        ship.moving_left = False


def update_bullets(screen, settings, ship, bullets, aliens):
    """更新子弹编组，对于超出上边界的子弹进行删除"""
    bullets.update()
    # 删除已经消失的子弹
    for bullet in bullets.copy():
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)
    check_bullets_aliens_collide(screen, settings, aliens, ship, bullets)


def update_aliens(screen, stats, settings, aliens, ship, bullets):
    check_aliens_edge(settings, aliens)
    """更新所有外星人的位置"""
    aliens.update()
    """检测飞船和外星人的碰撞"""
    if pygame.sprite.spritecollideany(ship, aliens):
        ship_hit(screen, stats, settings, aliens, ship, bullets)


def update_screen(screen, settings, ship, bullets, aliens):
    """更新屏幕，画出子弹、飞船、外星人新的位置"""
    screen.fill(settings.bg_color)
    for bullet in bullets.sprites():
        bullet.draw_bullet()
    ship.blitme()
    aliens.draw(screen)
    # 让最近绘制的屏幕可见
    pygame.display.flip()


def fire(screen, settings, ship, bullets):
    """开火，有子弹限制"""
    if len(bullets) < settings.bullets_allowed:
        new_bullet = Bullet(settings, screen, ship)
        bullets.add(new_bullet)


def get_alien_nums_x(settings, alien_width):
    """获得行上可以有多少外星人"""
    avaliable_space_x = settings.screen_width - 2 * alien_width
    num_alien_x = avaliable_space_x // (3 * alien_width)
    return num_alien_x


def get_alien_rows(settings, alien_height, ship_height):
    """获取有多少行外星人"""
    avaliable_space_y = settings.screen_height - 3 * alien_height - 2 * ship_height
    num_alien_y = avaliable_space_y // (2 * alien_height)
    return num_alien_y


def create_aliens(screen, settings, aliens_group, ship):
    """创建外星人编组"""
    alien = Alien(screen, settings)
    num_alien_x = get_alien_nums_x(settings, alien.rect.width)
    num_alien_y = get_alien_rows(settings, alien.rect.height, ship.rect.height)
    for y_num in range(num_alien_y):
        for x_num in range(num_alien_x):
            create_alien(screen, settings, x_num, y_num, aliens_group)


def create_alien(screen, settings, x_num, y_num, aliens_group):
    """创建外星人"""
    alien = Alien(screen, settings)
    alien.width = alien.rect.width
    alien.height = alien.rect.height
    alien.x = alien.width + 3 * alien.width * x_num
    alien.y = alien.height + 3 * alien.height * y_num
    alien.rect.x = alien.x
    alien.rect.y = alien.y
    aliens_group.add(alien)


def check_aliens_edge(settings, aliens):
    """检测外星人群体是否碰边"""
    for alien in aliens.sprites():
        if alien.check_edge():
            change_aliens_direction(settings, aliens)
            break


def change_aliens_direction(settings, aliens):
    """碰边，下降一格，转换方向"""
    for alien in aliens.sprites():
        alien.rect.y += settings.alien_down_speed
    settings.alien_direct *= -1


def check_bullets_aliens_collide(screen, settings, aliens, ship, bullets):
    """检测子弹和外星人的碰撞"""
    pygame.sprite.groupcollide(bullets, aliens, True, True)
    if len(aliens) == 0:
        bullets.empty()
        create_aliens(screen, settings, aliens, ship)


def ship_hit(screen, stats, settings, aliens, ship, bullets):
    stats.ship_left -= 1
    aliens.empty()
    bullets.empty()

    create_aliens(screen, settings, aliens, ship)
    ship.center_ship()
    sleep(0.5)
